import type { PositionType } from '@/hooks/usePosition';
import { defineStore } from 'pinia';
import { useMapStore } from './map';
import { reactive } from 'vue';
import { useTargetStore } from './target';
import { generateId } from '@/utils/id';

export interface Cargo {
  x: number;
  y: number;
  status: boolean;
}

export type DirectionType = 'left' | 'right' | 'up' | 'down';

export const useCargoStore = defineStore('cargo', () => {
  const cargos: Array<Cargo> = reactive([]);

  function addCargo(cargo: Cargo) {
    cargos.push(cargo);
  }
  const { isWall } = useMapStore();
  const { isTarget } = useTargetStore();
  /**
   * 使用位置信息创建箱子
   * 可能因为现在的箱子数据并不完整，所以先提供一个位置信息创建方法
   * @param cargo
   */
  function createCargo(position: { x: number; y: number }) {
    return {
      x: position.x,
      y: position.y,
      id: generateId(),
      status: isTarget(position),
    };
  }

  function _move(pos: PositionType, key: 'x' | 'y', moveValue: number) {
    const cargo = findCargo(pos);
    if (!cargo) return true;
    let newValue = cargo[key] + moveValue;
    const position = { ...cargo, [key]: newValue };
    if (isWall(position)) return false;
    if (isCargo(position)) return false;
    // 设置位置信息
    cargo[key] = newValue;
    cargo.status = isTarget(position);
    return true;
  }

  function findCargo(position: PositionType) {
    return cargos.find(
      (item) => item.x === position.x && item.y === position.y,
    );
  }

  function isCargo(position: PositionType) {
    const cargo = findCargo(position);
    return cargo !== undefined;
  }

  function cargoLeftMove(position: PositionType) {
    return _move(position, 'x', -1);
  }

  function cargoRightMove(position: PositionType) {
    return _move(position, 'x', 1);
  }

  function cargoUpMove(position: PositionType) {
    return _move(position, 'y', -1);
  }

  function cargoDownMove(position: PositionType) {
    return _move(position, 'y', 1);
  }

  function clearAllCargo() {
    cargos.splice(0, cargos.length);
  }

  const cargoMoves: {
    [key in DirectionType]: (position: PositionType) => boolean;
  } = {
    left: cargoLeftMove,
    right: cargoRightMove,
    up: cargoUpMove,
    down: cargoDownMove,
  };
  return {
    cargos,
    createCargo,
    addCargo,
    cargoLeftMove,
    cargoRightMove,
    cargoUpMove,
    cargoDownMove,
    cargoMoves,
    clearAllCargo,
  };
});
